package com.yxw.contentproviderdemo01;

import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ContentResolver cr = getContentResolver();
        Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME}, null, null, null);
        if (c != null) {
            while (c.moveToNext()) {
                int id = c.getInt(c.getColumnIndex("_id"));

                Log.i("info", "_id:" + id);
                Log.i("info", "name:" + c.getString(c.getColumnIndex("display_name")));

                Cursor c1 = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE}, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null);
//根据联系人ID查询出联系人的电话号码
                if(c1!=null){
                    while (c1.moveToNext()) {
                        int type = c.getInt(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                        if (type == ContactsContract.CommonDataKinds.Phone.TYPE_HOME) {
                            Log.i("inof", "家庭电话：" + c1.getString(c1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                        } else if (type == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
                            Log.i("inof", "手机：" + c1.getString(c1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                        }


                    }
                }

                c1.close();
                //根据联系人ID查询出联系人的邮箱地址
                Cursor cr2 = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Email.DATA, ContactsContract.CommonDataKinds.Email.TYPE}, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=" + id, null, null);

                if (cr2 != null) {
                    while (cr2.moveToNext()) {
                        int type = cr2.getInt(cr2.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                        if (type == ContactsContract.CommonDataKinds.Email.TYPE_WORK) {
                            Log.i("info", cr2.getString(cr2.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
                        }
                    }
                }
                cr2.close();

            }

        }
        c.close();
    }

}
